import pytest
import time
from pages.login_page import LoginPage
from typing import Dict
from pytest import Item
import allure

@pytest.fixture(scope="session")
def browser_context_args(browser_context_args, playwright, pytestconfig) -> Dict:  # noqa
    """
    添加context 上下文参数，默认每个页面加载cookies
    :param browser_context_args:
    :param playwright:
    :return:
    """
    return {
        "storage_state": pytestconfig.rootpath.joinpath("auth/state.json"),
        # "no_viewport": False,
        **browser_context_args,
        "viewport": {
            "width": 1840,
            "height": 900,
        },
        "record_video_size": {
            "width": 1440,
            "height": 900,
        }
    }

@pytest.fixture(scope="session", autouse=True)
def login_first(browser,base_url,pytestconfig):
    """全局先登录"""
    # base_url传到context
    context = browser.new_context(base_url=base_url)
    page = context.new_page()
    login = LoginPage(page)
    login.navigate()
    login.login(username="kuanglei", password="123456")
    # 等待登录成功
    # time.sleep(2)
    page.wait_for_load_state("networkidle")
    # 保存登录的cookie
    print(f"获取项目的根目录: {pytestconfig.rootpath}")
    storage_path = pytestconfig.rootpath.joinpath("auth/state.json")
    context.storage_state(path=storage_path)
    context.close()

@pytest.fixture(scope="module")
def login_context(browser, base_url, pytestconfig):
    """
    登录页面单独创建独立的page对象
    避免全局先登录加载cookie，导致有些打开登录页直接跳到首页去了
    :return:
    """
    context = browser.new_context(base_url=base_url)
    yield context
    context.close()

def pytest_runtest_call(item: Item): # noqa
    # 动态添加测试类的 allure.feature()
    if item.parent._obj.__doc__: # noqa
        allure .dynamic.feature(item.parent._obj.__doc__) # noqa
    # 动态添加测试用例的title 标题 allure.title()
    if item.function.__doc__: # noqa
        allure .dynamic.title(item.function.__doc__) # noqa






